package com.lin.fengxiu.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.lin.fengxiu.core.enumeration.OrderStatus;
import com.lin.fengxiu.dto.OrderAddressDTO;
import com.lin.fengxiu.util.CommonUtil;
import com.lin.fengxiu.util.GenericAndJson;
import lombok.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.*;
import org.hibernate.annotations.Where;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
 * @ClassName Order
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/4/2 6:35
 * @Version 1.0
 */
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Where(clause = "delete_time is null")
@Table(name = "`Order`")
public class Order extends BaseEntity{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * @Description TODO 订单编号
     */
    private String orderNo;
    private Long userId;
    private BigDecimal totalPrice;
    private Long totalCount;
    private Date expiredTime;
    private Date placedTime;
    private String snapImg;
    private String snapTitle;
    private String snapItems;
    private String snapAddress;
    private String prepayId;
    private BigDecimal finalTotalPrice;
    private Integer status;

    /**
     * @Description TODO 根据status获取对应的枚举值
     * @return
     */
    @JsonIgnore
    public OrderStatus getStatusEnum(){
        return OrderStatus.toType(this.status);
    }

    /**
     * @Description TODO 判断订单是否过期
     * @return
     */
    public Boolean needCancel(){
        if(!this.getStatusEnum().equals(OrderStatus.UNPAID)){
            return true;
        }
        boolean isOutOfDate = CommonUtil.isOutOfDate(this.getExpiredTime());
        if(isOutOfDate){
            return true;
        }
        return false;
    }

    public void setSnapItems(List<OrderSku> orderSkuList) {
        if (orderSkuList.isEmpty()) {
            return;
        }
        this.snapItems = GenericAndJson.objectToJson(orderSkuList);
    }

    public List<OrderSku> getSnapItems() {
        List<OrderSku> list = GenericAndJson.jsonToObject(this.snapItems, new TypeReference<List<OrderSku>>() {
        });
        return list;
    }

    public OrderAddressDTO getSnapAddress(){
        if(this.snapAddress == null){
            return null;
        }
        OrderAddressDTO orderAddressDTO = GenericAndJson.jsonToObject(this.snapAddress, new TypeReference<OrderAddressDTO>() {
        });
        return orderAddressDTO;
    }

    public void setSnapAddress(OrderAddressDTO address){
        this.snapAddress = GenericAndJson.objectToJson(address);
    }

}
